
var literal = {
    default_field: "--",
    defaultUrl: "#1"
}
var api = {
    getSchools: function(payload){
        //请求接口
        query('schools/', payload);
    },
    getNewsList: function(payload){
        //请求接口
        query('schools/', payload);
    },
    getPhotoList: function(payload){
        //请求接口
        query('schools/', payload);
    },
    getTeacherList: function(payload){
        //请求接口
        query('schools/', payload);
    }
}

var util = {
    getSchools: function(payload){
        api.getSchools({
            type: 'get',
            data: payload,
            success: function(res){
                if(res.errorCode == 200){
                    var data = res.data;
                    util.schoolListRender(data);
                }
            },
            error:function(res){
                $('.school-box .schoollist').empty();
                $('.school-box .schoollist').html(res.errorMsg);
            },
            fail: function(){
                $('.school-box .schoollist').empty();
                $('.school-box .schoollist').html('服务器开小差了!')
            },
            complete: function(){
                // 请求完成
            }
        })
    },
    getNewsList: function(payload){
        api.getNewsList({
            type: 'get',
            data: payload,
            success: function(res){
                if(res.errorCode == 200){
                    var data = res.data;
                    util.newsListRender(data);
                }
            },
            error:function(res){
                $('.newslist-box ul').empty();
                $('.newslist-box ul').html(res.errorMsg);
            },
            fail: function(){
                $('.newslist-box ul').empty();
                $('.newslist-box ul').html('服务器开小差了!')
            },
            complete: function(){
                // 请求完成
            }
        })
    },
    getPhotoList: function(payload, extend){
        api.getPhotoList({
            type: 'get',
            data: payload,
            success: function(res){
                if(res.errorCode == 200){
                    var data = res.data;
                    util.photoListRender(data, extend);
                }
            },
            error:function(res){
                $('.photolist-box .figurelist').empty();
                $('.photolist-box .figurelist').html(res.errorMsg);
            },
            fail: function(){
                $('.photolist-box .figurelist').empty();
                $('.photolist-box .figurelist').html('服务器开小差了!')
            },
            complete: function(){
                // 请求完成
            }
        })
    },
    schoolListRender: function(params){
        var data = params.items;
        var schoollist = $('.school-box .schoollist');
        var list = $('.modal .schoollist-item');
        var schoolBox =  $('.school-box');
        var pagelist = $('.modal .page').clone(true);
        schoollist.empty();// 清空学校列表
        schoolBox.find('.page').remove();// 清空分页内容
        if(params.total_items == 0){
            schoollist.html('暂无数据!');
            return false;
        }

        // 加载数据
        for(var i = 0, len =  data.length; i < len; i++){
            var newList = list.clone(true);
            var addressIcon = '<i></i>' + data[i].scarea_name || '<i></i>' + literal.default_field
            var url = DOMINURL + 'schools/' + data[i].e_name + '/';
            var orderUrl = DOMINURL + 'schools/' + data[i].e_name + '/' + 'baoming.html'

            newList.find('.school-logo a, .school-tit a, .detail-btn').attr('href', url || literal.defaultUrl);  // 学校链接
            newList.find('.school-logo img').attr('src', data[i].cover_img || literal.defaultUrl);  // 学校logo
            newList.find('.school-tit a').text(data[i].name || literal.default_field);  // 学校名称
            newList.find('.address-icon').html(addressIcon);  // 所在地区

            for(var key in data[i].type_name){    
                var tagColor = 'tag-color' + key;
                var newTag = '<em class="tag '+ tagColor +'">'+ data[i].type_name[key] +'</em>';
                
                newList.find('.school-type-list:eq(0)').append(newTag);
            }
            var school_type_name = getObj(data[i].school_type_name); // 学校性质
            var teach_name = getObj(data[i].teach_name);  // 课程体系
            var destination_name = getObj(data[i].destination_name);  // 留学国家
            
            newList.find('.school-type-list:eq(1) span').text(school_type_name || literal.default_field);
            newList.find('.school-type-list:eq(2) span').text(teach_name || literal.default_field);
            newList.find('.school-type-list:eq(3) span').text(destination_name || literal.default_field);
            newList.find('.school-type-list:eq(4) span').text(data[i].smalltext || literal.default_field);  // 学校简介
            newList.find('.order-btn').text(data[i].is_partner == '2' ? "升学指导" : "预约看校");
            newList.find('.order-btn').attr('href', orderUrl)

            newList.appendTo(schoollist);
        }

        if(params.limit < params.total_items){
            
            // 加载分页
            var prePage = params.current == 1 ? params.current : params.before;
            var nextPage = params.current == params.total_pages ? params.current : params.next;
            //var lastPage = literal.total_pages;
            var pages = getPages(params.current, params.total_pages);
            for(var n = 0; n < pages.length; n++){
                if(pages[n] > params.total_pages){ 
                    return false
                }
                pageItme = params.current == pages[n] ? '<b>'+ pages[n] +'</b>':'<a target="_self"  onclick="getCurrPage(this)" data-id="'+ pages[n] +'">' + pages[n] + '</a>'
                pagelist.find('.next').before(pageItme);
                pagelist.find('a b').html(params.total_items);
                pagelist.find('.next').attr('data-id', nextPage)
                // pagelist.find('.last-page').attr('data-id', lastPage)  // 尾页
                pagelist.find('.pre').attr('data-id', prePage);
                
                pagelist.appendTo(schoolBox);   
            }
        } else {
            schoolBox.find('.page').remove();
        }
        if(params.current == params.total_pages){
            $('.school-box .next').attr('onclick','').unbind('click');
        }
        if(params.current == 1){
            $('.school-box .pre').attr('onclick','').unbind('click');
        }
    },
    newsListRender: function(params){
        var data = params.items;
        var newslist = $('.newslist-box ul');
        var list = $('.modal ul li');
        var newsBox =  $('.newslist-box');
        var pagelist = $('.modal .page').clone(true);
        newslist.empty();// 清空学校列表
        newsBox.find('.page').remove();// 清空分页内容
        if(params.total_items == 0){
            newslist.html('暂无数据!');
            return false;
        }

        for(var i = 0, len = data.length; i < len; i++){
            var newList = list.clone(true);
            var url = DOMINURL + 'schools/' + data[i].e_name + '/'; // 新闻链接 待定
            newList.find('.newslist-img img').attr('src', data[i].cover_img);
            newList.find('.newslist-title').text(data[i].name || literal.default_field);
            newList.find('.newslist-title, .newslist-img a').attr('href', url);  // 新闻链接
            newList.find('.newslist-description').text(data[i].smalltext || literal.default_field)
            newList.find('.newslist-time').text(data[i].time || literal.default_field)

            newList.appendTo(newslist);    
        }

        if(params.limit < params.total_items){ 
            // 加载分页
            var prePage = params.current == 1 ? params.current : params.before;
            var nextPage = params.current == params.total_pages ? params.current : params.next;
            //var lastPage = literal.total_pages;
            var pages = getPages(params.current, params.total_pages);
            for(var n = 0; n < pages.length; n++){
                if(pages[n] > params.total_pages){ 
                    return false
                }
                pageItme = params.current == pages[n] ? '<b>'+ pages[n] +'</b>':'<a target="_self"  onclick="getNewsCurrPage(this,\'news\')" data-id="'+ pages[n] +'">' + pages[n] + '</a>'
                pagelist.find('.next').before(pageItme);
                pagelist.find('a b').html(params.total_items);
                pagelist.find('.next').attr('data-id', nextPage)
                // pagelist.find('.last-page').attr('data-id', lastPage)  // 尾页
                pagelist.find('.pre').attr('data-id', prePage);
                
                pagelist.appendTo(newsBox);   
            }
        } else {
            newsBox.find('.page').remove();
        }
        if(params.current == params.total_pages){
            $('.newslist-box .next').attr('onclick','').unbind('click');
        }
        if(params.current == 1){
            $('.newslist-box .pre').attr('onclick','').unbind('click');
        }
    },
    photoListRender: function(params, extend){
        var data = params.items;
        var photolist = $('.photolist-box .figurelist');
        var list = $('.modal .figurelist li');
        var photoBox =  $('.photolist-box');
        var pagelist = $('.modal .page').clone(true);
        var pageName = extend ? 'photo' : 'teacher';  // 判断分页类别
        photolist.empty();// 清空学校列表
        photoBox.find('.page').remove();// 清空分页内容
        if(params.total_items == 0){
            photolist.html('暂无数据!');
            return false;
        }

        for(var i = 0, len = data.length; i < len; i++){
            var newList = list.clone(true);
            newList.find('.figure-img img').attr('src', data[i].cover_img);
            newList.find('.figure-name').text(data[i].name || literal.default_field);
            newList.find('.figure-text').text(data[i].smalltext || literal.default_field);
            newList.appendTo(photolist);    
        }

        if(params.limit < params.total_items){
            // 加载分页
            var prePage = params.current == 1 ? params.current : params.before;
            var nextPage = params.current == params.total_pages ? params.current : params.next;
            //var lastPage = literal.total_pages;
            var pages = getPages(params.current, params.total_pages);
            for(var n = 0; n < pages.length; n++){
                if(pages[n] > params.total_pages){ 
                    return false
                }
                pageItme = params.current == pages[n] ? '<b>'+ pages[n] +'</b>':'<a target="_self"  onclick="getCurrPage(this,\''+ pageName +'\')" data-id="'+ pages[n] +'">' + pages[n] + '</a>'
                pagelist.find('.next').before(pageItme);
                pagelist.find('a b').html(params.total_items);
                pagelist.find('.next').attr('data-id', nextPage)
                // pagelist.find('.last-page').attr('data-id', lastPage)  // 尾页
                pagelist.find('.pre').attr('data-id', prePage);
                
                // pagelist.appendTo(photoBox);   
                photoBox.find('.figurelist').after(pagelist)
            }
        } else {
            photoBox.find('.page').remove();
        }
        if(params.current == params.total_pages){
            $('.photolist-box .next').attr('onclick','').unbind('click');
        }
        if(params.current == 1){
            $('.photolist-box .pre').attr('onclick','').unbind('click');
        }
    }
}

function getPages(currPage, total){  // 获取分页
    var page = []
    if(total < 5){
        for(var i = 1; i <= total; i++){
            page.push(i)
        }
    }
    if(total >= 5 && currPage <= 3){
        page = [1, 2, 3, 4, 5]
    }
    if(total >= 5 && currPage > 3 && currPage + 2 <= total){
        page = [currPage-2, currPage-1, currPage, currPage+1, currPage+2]
    }
    if(total >= 5 && currPage + 2 > total && currPage != total){
        page = [currPage -3, currPage - 2, currPage - 1, currPage, currPage + 1]
    } 
    if(total >= 5 && currPage == total && currPage + 2 > total ){
        page = [currPage - 4, currPage - 3, currPage - 2, currPage - 1, currPage ]
    }
    return page
}
function getObj(obj){  // 对象处理
    var str ='';
    if(obj instanceof Array){  // 判断是否为空数组
        return str
    } else {
        for(var key in obj){        
            str += obj[key]+' '
        } 
        return str
    }
}
function sieve (data) {
	for (var key in data) {
		if (data[key] === '') {
			delete data[key];
		}
    }
    return data
}

function getCurrPage(e, type){
    var id = parseInt($(e).attr('data-id'));
    // 更新ext，加载数据 
    ext['page'] = id;

    switch (type){
    case 'school':
        util.getNewsList(ext); //  获取学校数据
        break;
    case 'news':
        util.getNewsList(ext); //  获取学校新闻数据
        break;
    case 'photo':
        util.getPhotoList(ext, true); //  获取学校环境数据
        break;
    case 'teacher':
        util.getPhotoList(ext, false); //  获取学校师资数据
        break;
    default:
        util.getSchools(ext);//  默认调取学校数据
        break;
    }
}


function getFilter(e){  // 筛选内容
    // 更新ext，加载数据
    ext[$(e).attr('data-key')] = $(e).attr('data-value') == '0' ? '' : $(e).attr('data-value');
    sieve(ext);
    util.getSchools(ext);
}
function sub(){
    var search = $('.search-input input').val() == $('.search-input input').attr('data-default') ? '' : $('.search-input input').val();
    ext['search'] = search;
    sieve(ext);
    util.getSchools(ext);
    return false
}

$(function(){
    $('.filter-type li').click(function(){
        var _this = $(this);
        _this.addClass('active').siblings().removeClass('active');
        var id = '#' + _this.parents('.filter-type').attr('id')
        var  start = $('[data-target="'+ id +'"]').attr('data-state')
        if(start == 'true'){
            $(id).hide();
            $('[data-target="'+ id +'"]').attr('data-state', 'false');
            $('[data-target="'+ id +'"]').find('i').addClass('down-icon').removeClass('top-icon');
        }
    })
    $('.filter-title li').click(function(){
        var _this = $(this);
        var target = _this.attr('data-target');
        var state = _this.attr('data-state');
        _this.siblings().attr('data-state', "false");
        _this.siblings().find('i').addClass('down-icon').removeClass('top-icon');
        $('.filter-type').hide();
        if(state == 'false'){
            _this.attr('data-state', "true");
            _this.find('i').addClass('top-icon').removeClass('down-icon');
            $(target).show();
           
        } else {
            _this.attr('data-state', "false");
            _this.find('i').addClass('down-icon').removeClass('top-icon');
            $(target).hide();
        }
    })

})